<script setup>
import { ref, onMounted, computed } from 'vue'
import { ElMessageBox, ElMessage } from 'element-plus'
import { getAllDebts, addDebt, updateDebt, deleteDebt, calculateSummary } from '@/api/debt'

// 表格数据
const debtList = ref([])

// 控制弹窗显示
const dialogVisible = ref(false)

// 弹窗标题
const dialogTitle = ref('')

// 表单引用
const formRef = ref()

// 表单数据
const formData = ref({
  id: null,
  assetDescription: '',
  assetDirection: '+',
  summarySequence: null,
  variableName: ''
})

// 表单规则
const formRules = {
  id: [{ required: true, message: '请输入序号', trigger: 'blur' },
    { type: 'number', message: '序号必须为数字', trigger: 'blur' }
  ],
  assetDescription: [{ required: true, message: '请输入资产类说明', trigger: 'blur' }],
  assetDirection: [{ required: true, message: '请选择资产类方向', trigger: 'change' }],
  summarySequence: [{ required: true, message: '请输入汇总序号', trigger: 'blur' }],
  variableName: [{ required: true, message: '请输入变量名', trigger: 'blur' }]
}

// 是否为编辑模式
const isEdit = ref(false)

// 汇总相关数据
const selectedAssetDescription = ref('')
const calculationResult = ref('')
const calculationLoading = ref(false)

// 获取所有债务数据
const fetchDebtList = async () => {
  try {
    const res = await getAllDebts()
    console.log('获取债务数据成功:', res)
    if (res && res.code === 1) {
      debtList.value = res.data || []
    }
  } catch (error) {
    console.error('获取债务数据失败:', error)
  }
}

// 获取资产类说明与变量名的组合选项
const assetOptions = computed(() => {
  const uniqueDescriptions = [...new Set(debtList.value.map(item => item.assetDescription))];
  return uniqueDescriptions.map(description => {
    const item = debtList.value.find(debt => debt.assetDescription === description);
    return {
      label: `${item.variableName}（${description}）`,
      value: item.variableName,
      description: description
    };
  });
});

// 显示添加弹窗
const showAddDialog = () => {
  dialogTitle.value = '添加债务数据'
  isEdit.value = false
  formData.value = {
    id: null,
    assetDescription: '',
    assetDirection: '+',
    summarySequence: null,
    variableName: ''
  }
  dialogVisible.value = true
  clearFormValidation()
}

// 显示编辑弹窗
const showEditDialog = (row) => {
  dialogTitle.value = '编辑债务数据'
  isEdit.value = true
  formData.value = { ...row }
  dialogVisible.value = true
  clearFormValidation()
}

// 清空表单校验规则
const clearFormValidation = () => {
  if (formRef.value) {
    formRef.value.clearValidate()
  }
}

// 提交表单
const submitForm = async () => {
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        let res
        if (isEdit.value) {
          res = await updateDebt(formData.value)
        } else {
          res = await addDebt(formData.value)
        }
        
        if (res.code === 1) {
          ElMessage.success(`${isEdit.value ? '修改' : '添加'}成功`)
          dialogVisible.value = false
          fetchDebtList()
        } else {
          ElMessage.error(res.message || `${isEdit.value ? '修改' : '添加'}失败`)
        }
      } catch (error) {
        ElMessage.error(`${isEdit.value ? '修改' : '添加'}失败: ${error.message}`)
      }
    }
  })
}

// 删除债务数据
const handleDelete = (row) => {
  ElMessageBox.confirm(
    `确定要删除变量名为 "${row.variableName}" 的债务数据吗？`,
    '确认删除',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      const res = await deleteDebt(row.variableName)
      if (res.code === 1) {
        ElMessage.success('删除成功')
        fetchDebtList()
      } else {
        ElMessage.error(res.message || '删除失败')
      }
    } catch (error) {
      ElMessage.error(`删除失败: ${error.message}`)
    }
  }).catch(() => {
    // 取消删除
  })
}

// 计算汇总
const calculateSummaryData = async () => {
  if (!selectedAssetDescription.value) {
    calculationResult.value = ''
    return
  }
  
  calculationLoading.value = true
  try {
    // 根据资产类说明找到对应的债务数据
    const debtData = debtList.value.find(item => item.assetDescription === selectedAssetDescription.value)
    if (!debtData) {
      ElMessage.error('未找到对应的债务数据')
      return
    }
    
    const res = await calculateSummary(debtData)
    if (res.code === 1) {
      calculationResult.value = res.data || ''
    } else {
      ElMessage.error(res.message || '计算失败')
    }
  } catch (error) {
    ElMessage.error(`计算失败: ${error.message}`)
  } finally {
    calculationLoading.value = false
  }
}

// 当选择的资产类说明改变时触发计算
const handleVariableChange = () => {
  calculateSummaryData()
}

// 初始化数据
onMounted(() => {
  fetchDebtList()
})
</script>

<template>
  <div class="debt-page">
    <!-- 债务数据表格卡片 -->
    <el-card class="table-card">
      <template #header>
        <div class="card-header" style="text-align: center;">
          <span>债务统计表</span>
        </div>
      </template>
      
      <!-- 债务数据表格 -->
      <el-table :data="debtList" border style="width: 80%; margin: 0 auto;"> 
        <el-table-column prop="id" label="序号" width="80" align="center"></el-table-column>
        <el-table-column prop="assetDescription" label="资产类说明" width="220"></el-table-column>
        <el-table-column prop="assetDirection" label="资产类方向" width="120" align="center">
          <template #default="scope">
            <el-tag :type="scope.row.assetDirection === '+' ? 'success' : 'danger'">
              {{ scope.row.assetDirection }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="summarySequence" label="汇总序号" width="120" align="center"></el-table-column>
        <el-table-column prop="variableName" label="变量名" width="150" align="center"></el-table-column>
        <el-table-column label="操作" align="center">
          <template #default="scope">
            <el-button size="small" @click="showEditDialog(scope.row)">修改</el-button>
            <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
        
        <!-- 添加按钮行 -->
        <template #append>
          <div class="add-row" @click="showAddDialog">
            <span class="plus-icon">+</span>
            <span>添加新记录</span>
          </div>
        </template>
      </el-table>
    </el-card>
    
    <!-- 添加/编辑弹窗 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="500px">
      <el-form ref="formRef" :model="formData" :rules="formRules" label-width="100px">
        <el-form-item label="序号" prop="id">
          <el-input 
            v-model.number="formData.id" 
            type="number" 
            :disabled="isEdit"
            :placeholder="isEdit ? '序号不可修改' : '请输入序号'" 
          />
        </el-form-item>
        <el-form-item label="资产类说明" prop="assetDescription" >
          <el-input v-model="formData.assetDescription" />
        </el-form-item>
        <el-form-item label="资产类方向" prop="assetDirection">
          <el-radio-group v-model="formData.assetDirection">
            <el-radio label="+">+</el-radio>
            <el-radio label="-">-</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="汇总序号" prop="summarySequence">
          <el-input v-model.number="formData.summarySequence" type="number" />
        </el-form-item>
        <el-form-item label="变量名" prop="variableName">
          <el-input 
            v-model="formData.variableName" 
            :disabled="isEdit"
            :placeholder="isEdit ? '变量名不可修改' : '请输入变量名'" 
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
    
    <!-- 计算汇总区域 -->
    <el-card class="summary-card">
      <template #header>
        <el-row :gutter="20" style="margin-bottom: 20px; align-items: center;">
          <el-col :span="4">
            <span style="font-weight: bold;">计算汇总：</span>
          </el-col>
          <el-col :span="14">
            <el-select 
              v-model="selectedAssetDescription" 
              placeholder="请选择变量名"
              @change="handleVariableChange"
              style="width: 240px"
              clearable>
              <el-option
                v-for="option in assetOptions"
                :key="option.value"
                :label="option.label"
                :value="option.description">
              </el-option>
            </el-select>
          </el-col>
        </el-row>
      </template>
      <div class="summary-content">
        
        
        <!-- 显示选中资产类说明对应的数据 -->
        <div v-if="selectedAssetDescription" class="selected-data" style="margin-bottom: 20px;">
          <el-table 
            :data="debtList.filter(item => item.assetDescription === selectedAssetDescription)" 
            border
            style="width: 100%">
            <el-table-column prop="id" label="序号" width="80" align="center"></el-table-column>
            <el-table-column prop="assetDescription" label="资产类说明" width="220"></el-table-column>
            <el-table-column prop="assetDirection" label="资产类方向" width="120" align="center">
              <template #default="scope">
                <el-tag :type="scope.row.assetDirection === '+' ? 'success' : 'danger'">
                  {{ scope.row.assetDirection }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="summarySequence" label="汇总序号" width="120" align="center"></el-table-column>
            <el-table-column prop="variableName" label="变量名" width="150" align="center"></el-table-column>
          </el-table>
        </div>
        
        <!-- 汇总计算结果 -->
        <div v-if="selectedAssetDescription" class="calculation-result" style="margin: 0 10%">
          <span style="margin-right:10px;font-weight:bold">汇总=</span>
          <el-skeleton v-if="calculationLoading" :rows="1" animated />
          <span v-else>{{ calculationResult }}</span>
        </div>
      </div>
    </el-card>
  </div>
</template>

<style scoped>
.debt-page {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100%;
}

.table-card {
  margin-bottom: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.summary-card {
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.card-header {
  font-weight: bold;
  font-size: 24px;
  color: #303133;
  text-align: center;
}

.add-row {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 50px;
  background-color: #f5f7fa;
  cursor: pointer;
  color: #409eff;
  font-size: 14px;
  transition: all 0.3s;
}

.add-row:hover {
  background-color: #ecf5ff;
}

.plus-icon {
  font-size: 18px;
  font-weight: bold;
  margin-right: 5px;
}
</style>